package com.sky.wsp.spring.controller;

import com.alibaba.ttl.TransmittableThreadLocal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @desccription 测试子线程获取父线程的会话数据TransmittableThreadLocal
 * @auth wangshaopeng@talkweb.com.cn
 * @date 2023/2/17
 */
@RestController
@RequestMapping("thread_local")
public class ThreadLocalController {
    private static final TransmittableThreadLocal<String> THREAD_LOCAL = new TransmittableThreadLocal<>();

    /**
     * http://localhost:9090/thread_local/t?param=aaa&mainSleep=10&childSleep=2
     */
    @GetMapping("/t")
    public String thread(String param, Long mainSleep, Long childSleep) {
        THREAD_LOCAL.set(param);
        System.out.println("main thread begin -> " + param);

        try {
            Thread.sleep(mainSleep * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("child thread begin -> " + param + ":" + THREAD_LOCAL.get());
                try {
                    Thread.sleep(childSleep * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("child thread end ->  " + param + ":" + THREAD_LOCAL.get());
            }
        });

        thread.start();

        System.out.println("main thread end -> " + param);
        THREAD_LOCAL.remove();
        return param;
    }
}
